"""
 @author adun
 @date 2021/6/14 19:34
"""

from com.adun.mange_system.Student import Student
from com.adun.mange_system.MyEncoder import MyEncoder
import json

studentList = []


def main():
    recoverData()
    while True:
        method_name()
        getNum = int(input("请输入操作命令: "))
        if getNum == 1:
            addStu(studentList)
        elif getNum == 2:
            queryStu(studentList)
        elif getNum == 3:
            updateStu(studentList)
        elif getNum == 4:
            delStu(studentList)
        elif getNum == 5:
            printAll(studentList)
        elif getNum==6:
            saveToFile(studentList);
        elif getNum == 0:
            quitConfirm = input('真的要退出吗？（Yes or No）：')
            if quitConfirm=='Yes' or 'yes':
                break
            else:
                print("输入有误，请重新输入")

def method_name():
    print("+++++++++++++++++主操作菜单+++++++++++++++++++")
    print("1.添加学生")
    print("2.查询学生")
    print("3.修改学生")
    print("4.删除学生")
    print("5.查看列表所有信息")
    print("6.保存数据")
    print("0.退出系统")
    print("="*30)

def addStu(studentList):
    print("请输入学生信息:")
    name = input("姓名：")
    age = input("年龄：")
    addr = input("地址：")
    student = Student(name, age, addr)
    studentList.append(student)


def queryStu(studentList):
    name=input("请输入查询学生的姓名")
    for i in range(len(studentList)):
        if name.__eq__(studentList[i].getName()):
            studentList[i].print()
            break


def updateStu(studentList):
    name = input("请输入修改学生的姓名")
    for i in range(len(studentList)):
        if name.__eq__(studentList[i].getName()):
            name = input("姓名：")
            age = input("年龄：")
            addr = input("地址：")
            studentList[i].setName(name)
            studentList[i].setAge(age)
            studentList[i].setAddr(addr)
            break


def delStu(studentList):
    name = input("请输入删除学生的姓名")
    for i in range(len(studentList)):
        if name.__eq__(studentList[i].getName()):
            studentList.remove(studentList[i])
            break

def saveToFile(studentList):
    f=open("students.data",'w')
    print(studentList.__repr__())
    f.write(str(json.dumps(studentList,indent=4)))
    # f.write(str(studentList))
    f.close()

# 恢复数据
def recoverData():
    global studentList
    f = open('students.data')
    content = f.read()
    studentList = eval(content)
    f.close()

def printAll(studentList):
    i=1
    print("序号 -> | 姓名 | 年龄 | 地址 |")
    for stu in studentList:
        print("{0} -> | {1} | {2} | {3} |".format(i,stu.getName(),stu.getAge(),stu.getAddr()))
        i+=1

if __name__ == '__main__':
    main()
